package com.vecspace.web.servlet.model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * @author: wanghua
 */
public class HttpServletRequestWrapperEx extends HttpServletRequestWrapper {
	
	public HttpServletRequestWrapperEx(HttpServletRequest request) {
        super(request);
    }
	
	private String replaceScript(String value) {
        if(value == null || value.length()==0)return value;
        String tmpStr = value.toLowerCase();
        tmpStr = tmpStr.replaceAll(" ", "");
        //if(tmpStr.indexOf("<script>")>=0 && tmpStr.indexOf("</script>")>0){
        //	value = value.replaceAll("<script>", "&lt;script$gt;");
        //	value = value.replaceAll("<script>", "&lt;/script$gt;");
        //}
        return value;
    }
    /**
     *
     * @param name
     * @return
     */
	@Override
    public Object getAttribute(String name) {
        Object value = super.getAttribute(name);
        if (value instanceof String) {
            value = replaceScript(String.valueOf(value));
        }
        return value;
    }
    /**
     * 重写getParameter方法
     *
     * @param name
     * @return
     */
	@Override
    public String getParameter(String name) {
        String value = super.getParameter(name);
        if (value == null)
            return null;
        return replaceScript(value);
    }
    /**
     *
     * @param name
     * @return
     */
	@Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                values[i] = replaceScript(values[i]);
            }
        }
        return values;
    }
    /**
     * @return
     */
	@Override
    public Map<String, String[]> getParameterMap() {
        HashMap<String, String[]> newParamMap = new HashMap<String, String[]>();
        @SuppressWarnings("rawtypes")
		Map oldParamMap = super.getParameterMap();
        //paramMap = (HashMap<String, String[]>) paramMap.clone();
        for (@SuppressWarnings("rawtypes")
		Iterator iterator = oldParamMap.entrySet().iterator(); iterator.hasNext(); ) {
            @SuppressWarnings("unchecked")
			Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>) iterator.next();            
            String [] values = entry.getValue();
            for (int i = 0; i < values.length; i++) {
                if(values[i] instanceof String){
                    values[i] = replaceScript(values[i]);
                }
            } 
            newParamMap.put(entry.getKey(), values);
        }
        return newParamMap;
    }
}
